package app.server.project.main.service.service.cms;

import app.server.project.core.constants.CfgDef;
import app.server.project.core.constants.Def;
import app.server.project.core.http.CMSLstResp;
import app.server.project.main.service.bo.event.ClickEvent;
import app.server.project.main.service.constants.GlobalCfgKey;
import app.server.project.main.service.db.dao.cfg.GlobalCfgDao;
import app.server.project.main.service.db.entity.cfg.GlobalCfgEntity;
import app.server.project.main.service.dto.AddEnergyReq;
import app.server.project.main.service.dto.AddLvReq;
import app.server.project.main.service.dto.cms.UploadFileDto;
import app.server.project.main.service.service.EnergyService;
import app.server.project.main.service.service.lv.UserLvService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequiredArgsConstructor
@Service
@Slf4j
public class GMService {

    private final EnergyService energyService;
    private final UserLvService userLvService;
    private final ApplicationEventPublisher applicationEventPublisher;
    private final GlobalCfgDao globalCfgDao;
    private List<UploadFileDto> uploadFiles = new ArrayList<>();

    @Value("${spring.web.resources.static-locations}")
    private String staticPath;

    @Value("${spring.mvc.static-path-pattern}")
    private String pattern;

    @Value("${" + CfgDef.GameDir + ":/gamePkg/" + "}")
    private String gameDir;

    @Value("${" + CfgDef.imgDir + ":/imgDir/" + "}")
    private String imgDir;


    public void addLv(AddLvReq req) {
        var clickNum = this.userLvService.getLvClickNum(req.getLv(), req.getUserId());
        this.applicationEventPublisher.publishEvent(ClickEvent.of(req.getUserId(), clickNum, 1));
    }

    public void addEnergy(AddEnergyReq req) {
        energyService.addEnergyAndMax(req.getUserId(), req.getEnergy());
    }

    public CMSLstResp<UploadFileDto> getUploadFiles() {
        return CMSLstResp.of(uploadFiles, uploadFiles.size());
    }

    public String getVersion() {
        return this.globalCfgDao.getStr(GlobalCfgKey.CLIENT_VERSION);
    }


    public void upload(MultipartFile[] files, String version) {
        try {
            String path = staticPath + gameDir;
            FileUtil.del(path);
            FileUtil.mkdir(path);

            for (var file : files) {
                String fileName = file.getOriginalFilename();
                String tempPath = path + fileName;
                String tmpName = path + fileName;
                //删除文件夹
                FileUtil.del(tmpName.replace(".zip", ""));
                //写入本地文件
                FileUtil.writeBytes(file.getBytes(), tempPath);
                //解压本地文件
                ZipUtil.unzip(tempPath, tmpName.replace(".zip", ""));
                FileUtil.del(tempPath);
                GlobalCfgEntity globalCfgEntity = new GlobalCfgEntity();
                globalCfgEntity.setId(GlobalCfgKey.CLIENT_VERSION);
                globalCfgEntity.setVal(version);
                this.globalCfgDao.saveOrUpdate(globalCfgEntity);
                this.globalCfgDao.init();
                this.uploadFiles.add(0, UploadFileDto.of(globalCfgEntity.getVal(), new Date()));
                if (this.uploadFiles.size() >= 30) {
                    this.uploadFiles = this.uploadFiles.subList(0, 30);
                }
            }
        } catch (Exception e) {

        }

    }

    public String uploadSingleImg(MultipartFile file) {
        String path = staticPath + imgDir;
        StringBuilder domain = new StringBuilder(this.globalCfgDao.getStr(GlobalCfgKey.Domain));
        domain.append(this.pattern.replace("/**", ""));

        try {
            //取原文件名称
            String fileName = file.getOriginalFilename();
            String tempPath = path + fileName;
            //删除原文件
            //FileUtil.del(tempPath);
            //检查文件是否出现后缀
            var fileType = fileName.split("\\.");
            String finalName = StrUtil.EMPTY;
            if (fileType.length == Def.Zero) {
                finalName = IdUtil.fastSimpleUUID();
            } else {
                finalName = IdUtil.fastSimpleUUID() + "." + fileType[fileType.length - 1];
            }
            //写入本地文件
            FileUtil.writeBytes(file.getBytes(), path + finalName);
            //生成域名
            domain.append(imgDir).append(finalName);
            log.info("图片路径={}", domain.toString());
            return domain.toString();
        } catch (Exception e) {

        }
        return null;
    }
}
